(function init($) {

    if (typeof $.widget !== 'function' || !document.getElementById('main') || !document.getElementById('items')) {
        setTimeout(function() { init($); }, 200);
        return;
    }

    function shouldDisplay() {
        if (typeof localStorage === 'undefined') {
            return false;
        }

        if (!localStorage.likewall) {
            localStorage.likewall = '' + new Date().getTime();
            return false;
        } else {
            if (new Date() > parseInt(localStorage.likewall, 10)) {
                return true;
            }
        }
    }

    function createWidget() {
        "use strict";

        $.widget('ui.likewall', {
            options: {
            },

            _create: function() {
                var self = this;
                var windowWidth = $(window).width();
                var windowHeight = $(window).height();

                this._createHtml();

                this.background = $('<div/>').css({
                    width: windowWidth,
                    height: windowHeight,
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    'z-index': 1000,
                    'background-color': 'rgba(0, 0, 0, .55)'
                }).appendTo('body');

                var width = Math.min(windowWidth, 600);
                var height = Math.min(windowHeight, 432);

                this.element.css({
                    width: width,
                    height: height,
                    'background-color': '#fff',
                    'position': 'fixed',
                    'z-index': 1001,
                    'border-radius': 12,
                    'box-shadow': '0 0 12px #222',
                    display: 'block'
                }).css({
                    left: (windowWidth - width) / 2,
                    top: (windowHeight - height) / 2
                }).appendTo('body');

                var header = this.element.find('.header');

                var footer = this.element.find('.footer');
                
                var body = this.element.find('.body');
                var bodyPadding = 16;
                
                body.css({
                    padding: bodyPadding,
                    height: height - header.outerHeight(true) - footer.outerHeight(true) - (bodyPadding * 2),
                });

                this.element.on('click', '[data-dismiss]', function() {
                    if (self.element.find('[data-dismiss-forever]').is(':checked')) {
                        self.dismiss(365);
                    } else {
                        self.dismiss();
                    }
                    return false;
                });

                this.background.click(function() {
                    self.dismiss();
                });
                
                body.append('<fb:like-box href="' + this.options.pageUrl + '" width="' + body.width() + '" height="' + body.height() + '" show_faces="true" stream="false" border_color="#ffffff" header="false"></fb:like-box>');

                FB.XFBML.parse(body[0]);

                $(window).resize(function() {
                    self.setPosition();
                });

                FB.Event.subscribe('edge.create', function(likeUrl) {
                    if (likeUrl === self.options.pageUrl) {
                        self.dismiss(365);
                    }
                });
            },

            _createHtml: function() {
                this.element.append('<div class="header" style="font-size: 20; text-align: center; font-weight: bold; padding: 16px 0; border-bottom: 1px solid #ddd;">Auf unserer Facebook Seite findest Du noch mehr Gewinnspiele!</div><div class="body"></div><div class="footer" style="border-top: 1px solid #ddd; width: 100%; overflow: hidden;"><button data-dismiss style="border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); background-color: #F5F5F5; background-image: linear-gradient(to bottom, #FFFFFF, #E6E6E6); background-repeat: repeat-x; border-radius: 4px; border-style: solid; border-width: 1px; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05); color: #333333; cursor: pointer; display: inline-block; font-size: 14px; line-height: 20px; margin-bottom: 0; padding: 4px 12px; text-align: center; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); vertical-align: middle; margin: 6px 16px 6px 0; float: right; font-family: Arial;">Schließen</button><div style="vertical-align: middle; float: right; margin: 12px 16px; font-family: Arial;"><input type="checkbox" data-dismiss-forever> Nicht mehr anzeigen</div></div>');
            },

            setPosition: function() {
                this.background.width($(window).width());
                this.background.height($(window).height());

                this.element.css({
                    left: ($(window).width() - this.element.width()) / 2,
                    top: ($(window).height() - this.element.height()) / 2
                });
            },

            dismiss: function(days) {
                if (!days || isNaN(days)) {
                    var level = parseInt(localStorage.likewallDismissLevel, 10) || 0;
                    localStorage.likewallDismissLevel = level + 1;
                    days = Math.pow(2, level);
                } else {
                    localStorage.likewallDismissLevel = 0;
                }

                localStorage.likewall = new Date(+new Date() + days * 24 * 60 * 60 * 1000).getTime();

                this.element.remove();
                this.background.remove();
            }
        });
    }

    function loadFBApi() {
        window.fbAsyncInit = function() {
            $('body').append('<div data-ui-likewall="pageUrl: \'http://www.facebook.com/MegaBigaDeals\'" style="display: none;"></div>');
            $('[data-ui-likewall]').each(function() {
                var el = $(this);
                var options = (new Function('return {' + el.attr('data-ui-likewall') + '}'))();
                el.likewall(options);
            });
        };

        (function(d){
            var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement('script'); js.id = id; js.async = true;
            js.src = "//connect.facebook.net/en_US/all.js";
            ref.parentNode.insertBefore(js, ref);
        }(document));
    }

    if (shouldDisplay()) {
        createWidget();
        loadFBApi();        
    }
})(jQuery);
